
	const baseUrl = {
		host:"https://xiaokedou.shop",
		api:"/api/api/api6.php",
		qrcodeUrl:'/api/api/qrcode.php',
		static:"/api/api/",
	}
	var TimerInit     = null;
	var tagArr        = {};//防止多次点击使用的数组
	var token         = '';//全局的登录TOKEN
	var setStorageKEY ={
		wx_token :'token',//储存微信登录的状态的key 值为Boolean值
	}
	var firm_id = '';
	const SetFirmId=(id)=>{
		 firm_id = id
	}
	/**
	 * 获取详细单据
	*/
	const GetOrder=(order_id,firm_ids,print_mode)=>{
		var imgArr = []
		if(firm_ids && firm_ids.length>0){
			var firmId = firm_ids
		}else{
			var firmId = firm_id
		}
		
		
		if(print_mode == 4){
			var url = baseUrl.host + baseUrl.api +`?type=order_print_list&order_id=${order_id}&print_mode=${3}&share=1&firm_id=${firmId}`
			url   = encodeURIComponent(url)
			url   = baseUrl.host + baseUrl.qrcodeUrl +'?type=test&id='+url
			
		}else{
			
			var url = baseUrl.host + baseUrl.api +`?type=order_print_list&order_id=${order_id}&print_mode=${print_mode}&share=1&firm_id=${firmId}`
			url   = encodeURIComponent(url)
			url   = baseUrl.host + baseUrl.static +`wkhtmltoimage.php?url=${url}&t=`+new Date().getTime();
		}
		imgArr.push(url)
		uni.previewImage({
			urls:imgArr,
			fail:(e)=>{
			}
		})
	}
	/**
	 * 邀请二维码使用
	*/
	const GetInviteQrcode=(user_id)=>{
		var imgArr = []
		var url = baseUrl.host + baseUrl.api +converToUrl({
			type:'GetInviteQrcode',
			user_id:user_id,
			token:token,
		})
		
		url   = encodeURIComponent(url)
		url   = baseUrl.host + baseUrl.static +`wkhtmltoimage.php?url=${url}&mode=share&t=`+new Date().getTime();

		imgArr.push(url)
		uni.previewImage({
			urls:imgArr,
			fail:(e)=>{
			}
		})
	}
	const formatNumber=(number)=>{
		  if (number >= 1000000) {
			return (number / 10000).toFixed(1) + 'W';
		  } else if (number >= 1000) {
			return (number / 1000).toFixed(1) + 'K';
		  }
		  return number.toString();
	}
	
	
	
	/**
	* 设置系统剪贴板的内容。
	* */
	const setClipboardData=(data)=>{
		  uni.setClipboardData({
		  	data: data,
		  	success: function () {
		  		// console.log('success');
		  	},fail:function(res){
		  		console.log('setClipboardData',res);
		  	}
		  });
	}
	
	/**
	* 使用正则表达式来检测字符串中是否至少包含一个字母。
	* */
	const containsLetter=(str)=>{
	    return /[a-zA-Z]/.test(str);
	}
	/**
	* 搜索结果标红
	* text:被搜索的内容
	* keywordArr : 输入的关键字内容数组
	* */
	const highlightKeywords=(text, keywordArr)=>{
	    const highlighted = keywordArr.reduce((prevText, keyword) => {
	        const escapedKeyword = escapeRegExp(keyword);
	        const regex = new RegExp(escapedKeyword, 'gi');
	        return prevText.replace(regex, `<text style="color: red;" :selectable="true">${keyword}</text>`);
	    }, text);
	    
	    return highlighted;
	}
	const changeColumnColor = (id,colIndex)=>{
	
	  // 1. 移除所有列的背景色
	  const allTds = document.querySelectorAll('#'+id+' td');
	  allTds.forEach(td => td.style.backgroundColor = '');

	  // 2. 设置当前选中列的背景色
	  const targetCells = document.querySelectorAll('#'+id+` .col-${colIndex}`);
	  targetCells.forEach(td => {
		td.style.backgroundColor = '#0f66e01a'; // 黄色背景
	  });
	}

	//转义所有可能会干扰正则表达式的特殊字符
	function escapeRegExp(string) {
	    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');  // $& 意味着整个匹配的字符串
	}
	/**
	 * 获取今日日期
	 * todays : 被获取的时间日期
	 */
	const GetFormattedDate=(todays,hours ,minutes ,seconds )=>{
		
		if(todays==undefined){
			var today = new Date();
		}else{
			var today = new Date(todays);
		}
		// 格式化日期
		const year = today.getFullYear(); // 获取年份
		const month = (today.getMonth() + 1).toString().padStart(2, '0'); // 获取月份，+1因为getMonth()返回0-11
		const day = today.getDate().toString().padStart(2, '0'); // 获取日

		
		
		

		// 拼接为yyyy-mm-dd格式
		var  formattedDate = `${year}-${month}-${day}`
		if(hours){
			var data = today.getHours().toString().padStart(2, '0');
			formattedDate = formattedDate+` ${data}`
		}
		if(minutes){
			var data = today.getMinutes().toString().padStart(2, '0');
			formattedDate = formattedDate+`:${data}`
		}
		if(seconds){
			var data = today.getSeconds().toString().padStart(2, '0');
			formattedDate = formattedDate+`:${data}`
		}
		return formattedDate;
	}
	
	/**
	 * 检查微信登录
	 */
	const checkLogin=()=>{
		// // #ifdef H5
		// 	return true;
		// // #endif
		var tmp = token;
		if (!tmp) {
			return false;
		}
		return tmp;
	}


  /**
   * 数组序列化URL
   */
	const converToUrl = (requestParams,isUrl=true) => {
	  let params = [];
	  Object.entries(requestParams).forEach(([key, value]) => {
		  let param = key + '=' + value;
		  params.push(param);
	  });
	  if(isUrl==true){
		return '?' + params.join('&');
	  }
	  
	  return  params.join('&');
	}
 	
	 /**
	  * 保存token
	  */
	const setToken= (key) =>{
		token = key;
		uni.setStorage({
			key: setStorageKEY.wx_token,
			data: key,
			success: function () {
			}
		});
	}
	 /**
	  * 移除token
	  */
	const removeStorage = () =>{
		token = '';
		uni.removeStorage({
			key:setStorageKEY.wx_token,
		})
	}
	/**
	 * 消息弹窗
	 * @author yj
	 * 
	 * @param {String} title: 标题
	 * @param {String} icon: toast显示的图标, 可选值: success/error/fail/exception/loading/none
	 * @param {Number} duration: 窗口动画持续时间, 单位为ms
	 */
	const toast = (title, icon = 'none', duration = 2000) => {
	  uni.showToast({
		title,
		duration,
		icon
	  });
	}
	/**
	 * 显示模态弹窗
	 * @author yj
	 * 
	 * @param {String} title: 标题
	 * @param {String} icon: toast显示的图标, 可选值: success/error/fail/exception/loading/none
	 * @param {Number} duration: 窗口动画持续时间, 单位为ms
	 */
	const showModal = (title,content, success,showCancel=false) => {
	  uni.showModal({
		title,
		content,
		showCancel,
		success
	  });
	}
 
 
	/**
	 * 保留当前页面，跳转到应用内的某个页面
	 * @author yj
	 * 
	 * @param {String} url: 需要跳转的应用内非 tabBar 的页面的路径
	 * @param {String} animationType: 窗口显示的动画效果
	 * @param {Number} animationDuration: 窗口动画持续时间，单位为 ms
	 */
	const goto = (url, emit='',animationType = 'pop-in', animationDuration = 300) => {
	  uni.navigateTo({
		url:url,
		animationType:animationType,
		animationDuration:animationDuration,
		success: function(res) {
			if(emit){
				res.eventChannel.emit(emit.emit_name,emit.emit_value)
			}
		},
		fail: function(e) {}
	  })
	}
	 /**
	  * 关闭当前页面，跳转到应用内的某个页面。
	  * @author yj
	  * 
	  * @param {String} url: 需要跳转的应用内非 tabBar 的页面的路径，路径后可以带参数。参数与路径之间使用?分隔，参数键与参数值用=相连，不同参数用&分隔；如 'path?key=value&key2=value2'
	  */
	const redirectTo = (url,success_fun) => {
	   uni.redirectTo({
		 url:url,
		 success: function(res) {
			 if(success_fun){
				 success_fun()
			 }
		 },
		 fail: function(e) {}
	   })
	 }
	/**
	 * 关闭当前页面，返回上一页面或多级页面
	 * @author yj
	 * 
	 * @param {String} url: 需要跳转的应用内非 tabBar 的页面的路径
	 * @param {String} animationType: 窗口显示的动画效果
	 * @param {Number} animationDuration: 窗口动画持续时间，单位为 ms
	 */
	const goback = (emit='',delta = 1, animationType = 'pop-out', animationDuration = 300) => {
	 
	 
	  uni.navigateBack({
		delta,
		animationType,
		animationDuration,
		success: function(res) {
			
		},
		fail: function(e) {}
	  })
	}
	/**
	 * 跳转tab页面
	 * @param {string} url:欲跳转的tab地址。不是tab地址会跳转失败
	 * @param {string} emit_nama:向跳转页面发送信息的name键
	 * @param {string} emit_value:向跳转页面发送信息的value值 json格式 ：{content:that.optionData.text}
	 * */
	const switchTab =(url,emit='')=>{
		uni.switchTab(
		{
			url:url,
			success:function(res){
				if(emit){
					uni.$emit(emit.emit_nama,emit.emit_value)
				}
			}
		})
	}

	/**
	 * 获取系统信息，用以判断是否微信内或其他sdk
	 * */
	function getAppBaseInfo(){
		var AppBaseInfo = uni.getAppBaseInfo();
		//QQ的返回
		//{"fontSizeSetting":17,"language":"zh_CN","fontSizeScaleFactor":1,"version":"8.0.15","SDKVersion":"2.20.3","enableDebug":false,"host":{"env":"SDK","appId":"wxf0a80d0ac2e82aa7","version":302056976},"mode":"default","appId":"__UNI__39356A3","appName":"抽签助手","appVersion":"1.0.0","appVersionCode":"100","appLanguage":"zh-Hans","hostVersion":"8.0.15","hostLanguage":"zh-CN","hostName":"SDK","hostSDKVersion":"2.20.3"}
		//微信的返回
		//{"fontSizeSetting":17,"language":"zh_CN","fontSizeScaleFactor":1,"version":"8.0.32","SDKVersion":"2.30.0","enableDebug":false,"host":{"env":"WeChat","appId":"","version":402661426},"mode":"default","appId":"__UNI__39356A3","appName":"抽签助手","appVersion":"1.0.0","appVersionCode":"100","appLanguage":"zh-Hans","hostVersion":"8.0.32","hostLanguage":"zh-CN","hostName":"WeChat","hostSDKVersion":"2.30.0"}
		//微信模拟器返回
		//{"version":"8.0.5","language":"zh_CN","SDKVersion":"2.29.1","enableDebug":false,"fontSizeScaleFactor":0.75,"fontSizeSetting":16,"mode":"default","host":{"appId":"wxb812e2697195c7e7","env":"devtools","version":"1.06.2301160"},"appId":"__UNI__F847AC0","appName":"祝福语","appVersion":"1.0.0","appVersionCode":"100","appLanguage":"zh-Hans","hostVersion":"8.0.5","hostLanguage":"zh-CN","hostName":"devtools","hostSDKVersion":"2.29.1"}
		//浏览器返回
		//{"appId":"__UNI__39356A3","appName":"抽签助手","appVersion":"1.0.0","appVersionCode":"100","appLanguage":"zh-Hans","enableDebug":false,"hostName":"safari","hostVersion":"11.0","hostLanguage":"zh-CN","language":"zh-CN","SDKVersion":"","version":""}
		if(AppBaseInfo.host == undefined){
			return ''
		}else{
			return AppBaseInfo.host.appId
		}
		
	}
				
				
				
	const wx_login = (type='wx_login',retFun,fn_complete)=>{
		
		// #ifdef H5
			setToken('');
			if(retFun){
				retFun();
			}
		// #endif
		
		// #ifdef MP-WEIXIN
			wx.login({
			  success (res) {
				if (res.code) {
					get_request(
					 {
						 type:type,
						 js_code:res.code,
						 app : 1
					 },
					 (e)=>{
						setToken(e.token);
						if(retFun){
							retFun();
						}
					 },
					 ()=>{
						if(fn_complete){
							fn_complete();
						}
					 }
					 );
				} else {
					toast('登录失败！' + res.errMsg)
				}
			  }
			})
		// #endif
	}
	function isIE() {
	      const ua = window.navigator.userAgent;
	      const msie = ua.indexOf('MSIE ');
	      const trident = ua.indexOf('Trident/');
	
	      if (msie > 0) {
	        // IE 10 或以下
	        return true;
	      }
	
	      if (trident > 0) {
	        // IE 11
	        return true;
	      }
	
	      // 不是 IE 浏览器
	      return false;
	    }

	// 定义全局变量
	const requestMap = {}; // 用于按 type 管理请求

	/**
	 * 获取使用次数并回调（按 type 字段判断是否触发防抖或取消）
	 * @author yj
	 *
	 * @param {Object} data: 请求参数
	 * @param {Function} retFun: 成功回调函数
	 * @param {Function} fn_complete: 完成回调函数
	 * @param {Boolean} showLoading: 是否显示加载动画
	 * @param {String} host: 自定义请求地址
	 * @param {String} Loading: 加载动画的提示文字
	 * @param {Number} delay: 防抖延迟时间，默认 300ms
	 * @param {String} timer: 超时
	 */
	const get_request = (data, retFun, fn_complete, showLoading = true, host = "", Loading = "加载中", delay = 0,timer=60000) => {
		var type = data.type; // 获取请求的 type 字段
		if (data.type!=undefined && !type) {
			//console.error("请求参数中缺少 type 字段");
			//return;
			type = 'type'
			data.type = type
		}

		// 如果 type 已存在，则触发防抖和取消逻辑
		if (requestMap[type]) {
			// 清除之前的防抖定时器
			if (requestMap[type].debounceTimer) {
				clearTimeout(requestMap[type].debounceTimer);
			}

			// 取消之前的请求
			if (requestMap[type].abortController) {
				requestMap[type].abortController.abort();
			}

			// 设置新的防抖定时器
			requestMap[type].debounceTimer = setTimeout(() => {
				// 创建新的 AbortController
				requestMap[type].abortController = new AbortController();

				if (showLoading === true) {
					uni.showLoading({
						title: Loading,
						mask: true,
					});
				}


				lib(data, retFun, fn_complete, showLoading, host, requestMap[type].abortController, type,timer);
			}, delay);
		} else {
			// 如果 type 不存在，直接放行
			requestMap[type] = {}; // 初始化 type 的记录
			requestMap[type].abortController = new AbortController(); // 创建新的 AbortController

			if (showLoading === true) {
				uni.showLoading({
					title: Loading,
					mask: true,
				});
			}


			lib(data, retFun, fn_complete, showLoading, host, requestMap[type].abortController, type,timer);
		}
	};

	/**
	 * 发起请求的核心函数
	 * @param {Object} data: 请求参数
	 * @param {Function} retFun: 成功回调函数
	 * @param {Function} fn_complete: 完成回调函数
	 * @param {Boolean} showLoading: 是否显示加载动画
	 * @param {String} host: 自定义请求地址
	 * @param {AbortController} abortController: 用于取消请求的控制器
	 * @param {String} type: 请求的 type 字段
	 * @param {String} timer: 超时
	 */
	function lib(data, retFun, fn_complete, showLoading = true, host = "", abortController, type,timer=60000) {
		var tmp_data = data;
		if (token == '') {
			// token = uni.getStorageSync(setStorageKEY.wx_token)
		}
		if (tmp_data.firm_id == undefined) {
			tmp_data.firm_id = firm_id; // 仓库唯一ID
			tmp_data.appid   = firm_id; // 仓库唯一ID
		}
		
		tmp_data.token = token;
		tmp_data.applet = "h5";

		var body = converToUrl(tmp_data, false);
		var urlHost = host == "" ? baseUrl.host + baseUrl.api : host;

		uni.request({
			url: urlHost,
			method: 'POST',
			data: body,
			timeout: timer, // 超时时间
			header: {
				'content-type': 'application/x-www-form-urlencoded',
			},
			signal: abortController.signal, // 绑定 AbortController
			success: (res) => {
				if (showLoading === true) {
					uni.hideLoading({
						fail: function (e) {},
					});
				}
				if (res.data.code == 301) {
					removeStorage();
					toast(res.data.msg);
					goto('/pages/login/login');
					return;
				}
				if (undefined == res.data.code) {
					toast("网络出错了...");
					if (fn_complete) {
						fn_complete();
					}
					return;
				}
				if (res.data.code == 101010 || res.data.code == 121212) {
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel: false,
						confirmText: '确定',
						success: () => {
							if (fn_complete) {
								fn_complete(res.data);
							}
						},
					});
					return;
				}
				if (res.data.code != 0) {
					toast(res.data.msg);
					if (fn_complete) {
						fn_complete(res.data);
					}
					return;
				}
				retFun && retFun(res.data);
			},
			fail: (err) => {
				if (err.errMsg === "request:fail abort") {
					console.log("请求被取消");
				} else {
					toast("请求失败，请重试");
				}
			},
			complete: () => {
				if (showLoading === true) {
					uni.hideLoading({
						fail: function (e) {},
					});
				}
				if (fn_complete) {
					fn_complete();
				}
				// 请求完成后清理对应的 type 记录
				if (requestMap[type]) {
					delete requestMap[type].abortController; // 清除 AbortController
					delete requestMap[type].debounceTimer; // 清除防抖定时器
				}
			},
		});
	}
	/**
	 * 录音计时
	* @param {Boolean} start :是否启动或清除
	* @param {Function} fn :每次计时的回调函数
	* @param {number} time :持续的时长 /秒
	 */
	const recordingTimer=(start=false,fn,time=60,fail_fn,interval=1000)=>{ 
		clearInterval(TimerInit) 
		var that = this 
		if (start != false) { 
			TimerInit = setInterval(function() { //将计时器赋值给 TimerInit 
				time--;
				fn(time);
				
				if(time <= 0 && time>-1){
					clearInterval(TimerInit) 
					fail_fn && fail_fn()
				}
			}, interval); 
		} else { 
			clearInterval(TimerInit) 
			fail_fn && fail_fn()
		} 
	}
		
	/**
	 * 文件上传
	* @param {string} filePath :图片路径
	* @param {object} formData :上次参数
	 */
	const uploadFile=(filePath,formData,success_fn,complete_fn,showLoading=true,loadTitle='加载中')=>{
		if(showLoading==true){
			uni.showLoading({
				title: loadTitle,
				mask : true
			});
		}
		formData.token = token;
			// #ifndef H5
				//formData.appid = uni.getAccountInfoSync().miniProgram.appId;
			// #endif
			// #ifdef H5
				//formData.appid = 1;
			// #endif
		uni.uploadFile({
			url: baseUrl.host+baseUrl.api ,
			name:"file",
			filePath:filePath,
			formData:formData,
			timeout:60000,//超时时间
			success: (res) => {
				if(!res.data){
					return;
				}
				var res = JSON.parse(res.data)
				
				if(showLoading==true){
					uni.hideLoading({
						  fail: function(e) {}
					});
				}
				if(res.code == 0){
					success_fn(res)
				}else if(res.code == 101010){
					uni.showModal({
						title:'提示',
						content:res.msg,
						showCancel:false,
						confirmText:'确定',
						success: () => {
							if(complete_fn){
								complete_fn(res);
							}
						}
					});
					return ;
				}else{
					toast(res.msg)
				}
			},
			fail(res){
				if(res.data){
					toast(res.data.msg)
				}
			},
			complete:(res)=>{
				if(complete_fn){
					complete_fn();
				}
				if(showLoading==true){
					uni.hideLoading({
						  fail: function(e) {}
					});
				}
			}
		})
	}

	/**
	* 防止处理多次点击,需要到引用页面挂载一个变量名为：tagArr 类型为数组 。比如：tagArr:[]
	* @param {string} tag :当前执行函数的标志，防止一个页面过多函数分不清
	* @param {Function} fn :是点击后需要执行的函数
	* @param {Array} body :是函数需要传的参数 {name:value}
	 */
	const noMultipleClicks=(tag,fn, ...data)=>{
		let that = this;
		if(undefined == tagArr[tag]){
			tagArr[tag] = true;
		}
		if (tagArr[tag]) {
			tagArr[tag]= false;
			if(data && data.length>0) {
				
					fn(...data);
				
			} else {
					fn();
			}
			setTimeout(()=> {
				tagArr[tag]= true;
			}, 200)
		} else {
			//  这里是重复点击的判断
		}
	}
	/**
	 * 获取年月日
	 * timestamp : 被获取的10位时间戳
	 */
	const formatTime=(timestamp)=>{
		const date = new Date(timestamp * 1000);
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	}
	/**
	 * 获取其他时间
	 * timestamp : 被获取的10位时间戳
	 */
	const formatWechatTime = (timestamp) => {
		// 统一转换为数字类型，并确保是10位秒级时间戳
		let ts = Number(timestamp);
		if (isNaN(ts) || ts.toString().length !== 10) {
			// 如果转换失败或不是10位，尝试直接解析原值（可能是毫秒或其他格式）
			const date = new Date(timestamp);
			if (isNaN(date.getTime())) {
				return "无效日期"; // fallback处理
			}
			return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
		}
		
		// 以下逻辑使用秒级时间戳（ts变量）
		const now = Math.floor(Date.now() / 1000); // 当前秒级时间戳
		const today = Math.floor(new Date().setHours(0, 0, 0, 0) / 1000); // 今天0点（秒）
		const yesterday = today - 86400; // 昨天0点（秒）
		
		// 计算本周一0点（秒）
		const todayDate = new Date();
		const monday = new Date(todayDate);
		monday.setDate(todayDate.getDate() - (todayDate.getDay() || 7) + 1);
		monday.setHours(0, 0, 0, 0);
		const weekStart = Math.floor(monday.getTime() / 1000);

		if (ts >= today) {
			return new Date(ts * 1000).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
		} else if (ts >= yesterday) {
			return '昨天';
		} else if (ts >= weekStart) {
			const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
			const weekDay = new Date(ts * 1000).getDay();
			return '周' + weekDays[weekDay];
		} else {
			return new Date(ts * 1000).toLocaleDateString('zh-CN');
		}
	}
	//注册定义的方法
	export const util= {
	  baseUrl,
	  setClipboardData,
	  toast,
	  goto,
	  goback,
	  redirectTo,
	  get_request,
	  recordingTimer,
	  token,
	  switchTab,
	  uploadFile,
	  setStorageKEY,
	  setToken,
	  converToUrl,
	  wx_login,
	  checkLogin,showModal,removeStorage,noMultipleClicks,highlightKeywords,GetFormattedDate,formatNumber,
	  containsLetter,SetFirmId,isIE,changeColumnColor,GetOrder,GetInviteQrcode,formatTime,formatWechatTime
	}
